package com.demo.mykotlin.activity

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.demo.mykotlin.ActivityCollector

/**
 * 活动基类
 * @author wen66to88@163.com
 * @date 2020/5/27 - 14:02
 */
@SuppressLint("Registered")
open class BaseActivity : AppCompatActivity() {
    lateinit var receiver: ForceOffLineReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("BaseActivity", javaClass.simpleName)
        ActivityCollector.addActivity(this)
    }

    override fun onResume() {
        super.onResume()
        val interFilter = IntentFilter()
        interFilter.addAction("com.demo.mykotlin.FORCE_OFFLINE")
        receiver = ForceOffLineReceiver()
        registerReceiver(receiver, interFilter)
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(receiver)
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }

    /**
     * 离线接收
     */
    inner class ForceOffLineReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            AlertDialog.Builder(context).apply {
                setTitle("警告")
                setMessage("你即将下线，请尝试重新登录！")
                setCancelable(false)
                setPositiveButton("ok") { _, _ ->
                    //销毁所有Activity
                    ActivityCollector.finishAll()
                    //跳转到登录页面
                    val i = Intent(context, LoginActivity::class.java)
                    context.startActivity(i)
                }
                show()
            }
        }
    }
}